#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
XCQuant 快速上手演示脚本
这个脚本展示了如何使用XCQuant进行量化交易的基本功能
"""

import sys
import os
import time
from datetime import datetime, timedelta

# 添加项目路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from xcquant.backtesting.mock_exchange import MockExchange
from xcquant.backtesting.mock_managers import MockOrderManager, MockAccountManager
from xcquant.strategies.enhanced_grid_strategy import EnhancedGridStrategy
from xcquant.core.trade_analyzer import TradeAnalyzer

def print_separator(title=""):
    """打印分隔线"""
    print("\n" + "="*60)
    if title:
        print(f"  {title}")
        print("="*60)

def demo_basic_trading():
    """演示基本交易功能"""
    print_separator("基本交易功能演示")
    
    # 1. 初始化模拟交易所
    exchange = MockExchange()
    print("✓ 模拟交易所初始化完成")
    
    # 2. 设置初始价格
    symbol = "BTC-USDT"
    initial_price = 50000.0
    exchange.set_price(symbol, initial_price)
    print(f"✓ 设置 {symbol} 初始价格: ${initial_price:,.2f}")
    
    # 3. 初始化账户管理器
    account_manager = MockAccountManager()
    account_manager.update_balance("USDT", 10000.0, "deposit")  # 存入10000 USDT
    balance_info = account_manager.get_balance('USDT')
    print(f"✓ 账户初始化完成，USDT余额: ${balance_info['total']:,.2f}")
    
    # 4. 初始化订单管理器
    order_manager = MockOrderManager()
    print("✓ 订单管理器初始化完成")
    
    # 5. 下单测试
    print("\n--- 下单测试 ---")
    
    # 市价买单
    buy_order_id = order_manager.place_order(
        symbol=symbol,
        side="buy",
        order_type="market",
        quantity=0.1,  # 买入0.1 BTC
        price=None
    )
    print(f"✓ 市价买单已提交: {buy_order_id}")
    
    # 限价卖单
    sell_price = initial_price * 1.05  # 高5%卖出
    sell_order_id = order_manager.place_order(
        symbol=symbol,
        side="sell",
        order_type="limit",
        quantity=0.05,  # 卖出0.05 BTC
        price=sell_price
    )
    print(f"✓ 限价卖单已提交: {sell_order_id}, 价格: ${sell_price:,.2f}")
    
    # 6. 查看账户状态
    print("\n--- 账户状态 ---")
    usdt_balance_info = account_manager.get_balance("USDT")
    btc_balance_info = account_manager.get_balance("BTC")
    print(f"USDT 余额: ${usdt_balance_info['total']:,.2f}")
    print(f"BTC 余额: {btc_balance_info['total']:.6f}")
    
    # 7. 查看订单状态
    print("\n--- 订单状态 ---")
    open_orders = order_manager.get_open_orders(symbol)
    if open_orders:
        for order in open_orders:
            price_str = f"${order.get('price', 0):,.2f}" if order.get('price') else "市价"
            print(f"订单 {order['order_id']}: {order['side']} {order['quantity']} {symbol} @ {price_str} - {order['status']}")
    else:
        print("暂无未完成订单")

def demo_grid_strategy():
    """演示网格策略"""
    print_separator("网格策略演示")
    
    # 1. 初始化组件
    exchange = MockExchange()
    account_manager = MockAccountManager()
    order_manager = MockOrderManager()
    
    # 2. 设置初始资金和价格
    symbol = "BTC-USDT"
    initial_price = 50000.0
    initial_balance = 10000.0
    
    exchange.set_price(symbol, initial_price)
    account_manager.update_balance("USDT", initial_balance, "deposit")
    
    print(f"✓ 初始设置完成")
    print(f"  交易对: {symbol}")
    print(f"  初始价格: ${initial_price:,.2f}")
    print(f"  初始资金: ${initial_balance:,.2f} USDT")
    
    # 3. 初始化网格策略
    strategy_config = {
        'symbol': symbol,
        'grid_count': 10,           # 网格数量
        'price_range_percent': 0.1, # 价格范围 ±10%
        'base_order_size': 50.0,    # 基础订单金额
        'profit_ratio': 0.005,      # 利润比例 0.5%
        'type': 'spot',             # 现货交易
        'exchange': 'mock',         # 模拟交易所
        'enabled': True
    }
    
    # 创建一个简化的策略实例，避免复杂的依赖
    print(f"✓ 网格策略配置完成")
    print(f"  网格数量: {strategy_config['grid_count']}")
    print(f"  价格范围: ±{strategy_config['price_range_percent']*100:.1f}%")
    print(f"  基础订单金额: ${strategy_config['base_order_size']:,.2f}")
    
    # 4. 模拟网格交易逻辑
    print("\n--- 模拟网格交易 ---")
    grid_count = strategy_config['grid_count']
    price_range = initial_price * strategy_config['price_range_percent']
    price_min = initial_price - price_range
    price_max = initial_price + price_range
    grid_spacing = (price_max - price_min) / grid_count
    
    print(f"价格区间: ${price_min:,.2f} - ${price_max:,.2f}")
    print(f"网格间距: ${grid_spacing:,.2f}")
    
    # 模拟几个网格订单
    grid_orders = []
    for i in range(3):  # 只模拟3个网格
        buy_price = price_min + i * grid_spacing
        sell_price = buy_price * (1 + strategy_config['profit_ratio'])
        
        # 模拟下买单
        buy_order_id = order_manager.place_order(
            symbol=symbol,
            side='buy',
            order_type='limit',
            quantity=strategy_config['base_order_size'] / buy_price,
            price=buy_price
        )
        
        grid_orders.append({
            'level': i,
            'buy_price': buy_price,
            'sell_price': sell_price,
            'buy_order_id': buy_order_id,
            'status': 'buy_pending'
        })
        
        print(f"网格 {i+1}: 买入价 ${buy_price:,.2f}, 卖出价 ${sell_price:,.2f}")
    
    print(f"✓ 已设置 {len(grid_orders)} 个网格订单")
    
    # 5. 模拟价格波动和网格交易
    print("\n--- 模拟价格波动 ---")
    price_changes = [
        (49000, "价格下跌到 $49,000"),
        (51000, "价格上涨到 $51,000"),
        (48000, "价格下跌到 $48,000"),
        (52000, "价格上涨到 $52,000"),
        (50000, "价格回到 $50,000")
    ]
    
    for new_price, description in price_changes:
        print(f"\n{description}")
        exchange.set_price(symbol, new_price)
        
        # 模拟网格交易逻辑
        for grid in grid_orders:
            if grid['status'] == 'buy_pending' and new_price <= grid['buy_price']:
                # 模拟买单成交
                grid['status'] = 'buy_filled'
                print(f"  ✓ 网格 {grid['level']+1} 买单成交: ${grid['buy_price']:,.2f}")
                
                # 立即下卖单
                sell_order_id = order_manager.place_order(
                    symbol=symbol,
                    side='sell',
                    order_type='limit',
                    quantity=strategy_config['base_order_size'] / grid['buy_price'],
                    price=grid['sell_price']
                )
                grid['sell_order_id'] = sell_order_id
                grid['status'] = 'sell_pending'
                
            elif grid['status'] == 'sell_pending' and new_price >= grid['sell_price']:
                # 模拟卖单成交
                grid['status'] = 'completed'
                profit = (grid['sell_price'] - grid['buy_price']) * (strategy_config['base_order_size'] / grid['buy_price'])
                print(f"  ✓ 网格 {grid['level']+1} 卖单成交: ${grid['sell_price']:,.2f}, 盈利: ${profit:.2f}")
        
        # 显示当前状态
        usdt_balance_info = account_manager.get_balance("USDT")
        btc_balance_info = account_manager.get_balance("BTC")
        usdt_balance = usdt_balance_info['total']
        btc_balance = btc_balance_info['total']
        total_value = usdt_balance + btc_balance * new_price
        
        print(f"  USDT: ${usdt_balance:,.2f}")
        print(f"  BTC: {btc_balance:.6f}")
        print(f"  总价值: ${total_value:,.2f}")
        print(f"  盈亏: ${total_value - initial_balance:+,.2f} ({(total_value/initial_balance-1)*100:+.2f}%)")
        
        time.sleep(0.5)  # 暂停0.5秒
    
    # 6. 显示网格统计
    print("\n--- 网格统计 ---")
    completed_grids = [g for g in grid_orders if g['status'] == 'completed']
    pending_grids = [g for g in grid_orders if g['status'] in ['buy_pending', 'sell_pending', 'buy_filled']]
    
    print(f"完成交易网格: {len(completed_grids)}")
    print(f"待成交网格: {len(pending_grids)}")
    print(f"网格利用率: {len(completed_grids)/len(grid_orders)*100:.1f}%")

def demo_performance_analysis():
    """演示性能分析"""
    print_separator("性能分析演示")
    
    # 创建性能分析器
    analyzer = TradeAnalyzer()
    
    # 模拟一些交易记录
    trades = [
        {'symbol': 'BTC-USDT', 'side': 'buy', 'amount': 0.1, 'price': 50000, 'timestamp': '2024-01-01 10:00:00'},
        {'symbol': 'BTC-USDT', 'side': 'sell', 'amount': 0.05, 'price': 52000, 'timestamp': '2024-01-01 11:00:00'},
        {'symbol': 'BTC-USDT', 'side': 'sell', 'amount': 0.05, 'price': 51000, 'timestamp': '2024-01-01 12:00:00'},
        {'symbol': 'BTC-USDT', 'side': 'buy', 'amount': 0.08, 'price': 49000, 'timestamp': '2024-01-01 13:00:00'},
        {'symbol': 'BTC-USDT', 'side': 'sell', 'amount': 0.08, 'price': 53000, 'timestamp': '2024-01-01 14:00:00'},
    ]
    
    print("✓ 模拟交易记录:")
    for i, trade in enumerate(trades, 1):
        print(f"  {i}. {trade['side'].upper()} {trade['amount']} BTC @ ${trade['price']:,}")
    
    # 添加交易记录
    for trade in trades:
        analyzer.add_trade(
            symbol=trade['symbol'],
            side=trade['side'],
            amount=trade['amount'],
            price=trade['price'],
            timestamp=datetime.strptime(trade['timestamp'], '%Y-%m-%d %H:%M:%S')
        )
    
    # 生成性能报告
    print("\n--- 性能报告 ---")
    report = analyzer.generate_report()
    
    print(f"总交易次数: {report['total_trades']}")
    print(f"盈利交易: {report['profitable_trades']}")
    print(f"亏损交易: {report['losing_trades']}")
    print(f"胜率: {report['win_rate']:.2%}")
    print(f"总盈亏: ${report['total_pnl']:,.2f}")
    print(f"平均盈亏: ${report['avg_pnl']:,.2f}")
    print(f"最大盈利: ${report['max_profit']:,.2f}")
    print(f"最大亏损: ${report['max_loss']:,.2f}")

def main():
    """主函数"""
    print("🚀 欢迎使用 XCQuant 量化交易平台!")
    print("本演示将展示平台的主要功能...")
    
    try:
        # 1. 基本交易功能演示
        demo_basic_trading()
        
        print("\n" + "="*60)
        print("继续网格策略演示...")
        time.sleep(1)
        
        # 2. 网格策略演示
        demo_grid_strategy()
        
        print("\n" + "="*60)
        print("继续性能分析演示...")
        time.sleep(1)
        
        # 3. 性能分析演示
        demo_performance_analysis()
        
        print_separator("演示完成")
        print("🎉 恭喜! 您已经完成了 XCQuant 的快速上手演示")
        print("\n接下来您可以:")
        print("1. 查看 examples/ 目录下的更多示例")
        print("2. 阅读文档了解更多高级功能")
        print("3. 开始编写您自己的交易策略")
        print("4. 运行 python examples/web_dashboard.py 启动Web界面")
        
    except KeyboardInterrupt:
        print("\n\n演示被用户中断")
    except Exception as e:
        print(f"\n❌ 演示过程中出现错误: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    main()